#include "cache_handle.h"
QueueHandle_t cache_queue_handle;
static TaskHandle_t cache_handle;

static void print_data_hex(uint8_t *data, int len)
{   
    for (int i = 0; i < len; i++) 
    {
        printf(" %02x", data[i]);
    }
    printf(", len1: %d\n", len);
}

u16 cache_read(u8 *g_uart_buf,DATA_SOURCE *source)
{
  cache_param *buffer = NULL;
  uint16_t received=0;
  if(xQueueReceive(cache_queue_handle,&buffer,portMAX_DELAY))
  {
    if (buffer != NULL)
    {
        memcpy(g_uart_buf,buffer->data,buffer->len);
        received = buffer->len;
        *source = buffer->source;
        vPortFree(buffer->data);
        vPortFree(buffer);
        return received;
    }
    else
    {
        return 0;
    }
  }
  else
  {
    return 0;
  }  
}

//缓存处理函数
void cache_task()
{
    LOG_INFO("disp_task : enter cache_task()\n");
    u8 g_uart_buf[BUF_CACHE_SIZE];
    cache_queue_handle = xQueueCreate(20,sizeof(cache_param *));
    while(1)
    {
        uint16_t received=0;
        DATA_SOURCE source = NONE_SOURCE;
        bzero(g_uart_buf,0);
        if((received = cache_read(g_uart_buf,&source)) != 0)
        {
            if((g_uart_buf[0]==PACKET_HEADER))//校验包头
            {
                analysis_receive_message(g_uart_buf,received,source);
            }
            else
            {
                LOG_INFO("PACKET_HEADER err\n");
                print_data_hex(g_uart_buf,received);
            } 
        }
    }
}

void cache_init(void)
{
    printf("cache_init():enter\n");
    xTaskCreate(cache_task, "cache_task",CACHE_LOGIC_SIZE, NULL, TASK_PROP_CACHE, &cache_handle);
}
